import fg from "fast-glob";
import fs from "fs-extra";
import { BaseTask, TaskResult } from "./BastTask.js";
import { toolchain } from '../../toolchain.js';
import path from "path";
import { gzip, md5, replaceInFileOrThrow } from "../../tools/vendor.js";
import { CommonEnv } from "../CommonEnv.js";

/**json不打ab包，直接上传到cdn，需在cfg.json中配置开启，目前仅在webgl模型下使用 */
export class JsonBundleTask extends BaseTask<void> {
    async run(): Promise<TaskResult<void>> {
        const jsonInsteadOfAB = toolchain.params.channelCfg.jsonInsteadOfAB;
        if (jsonInsteadOfAB) {
            // 需要主动配置使用原始json而非ab包才生效
            const jsonRoot = path.join(toolchain.params.workSpacePath, 'Assets/AssetSources/data');
            let jsons: string[] = ['bundle.json'];
            if (jsonInsteadOfAB == 'individual') {
                jsons = await fg('*.json', { cwd: jsonRoot, ignore: ['bundle.json'] });
            }            

            const assetRoot = path.join(toolchain.params.uploadPath, toolchain.unity.getAssetsDir());
            const dstRoot = path.join(assetRoot, 'data');
            await fs.ensureDir(dstRoot);

            const md5Book: Record<string, string> = {};
            for (const json of jsons) {
                const jsonFile = path.join(jsonRoot, json);
                const content = await fs.readFile(jsonFile);
                const fileMd5 = md5(content).substring(0, 10);
                const fileName = path.basename(json, '.json');
                md5Book[fileName] = fileMd5;
                const versionedFile = path.join(dstRoot, fileName + '_' + fileMd5 + '.json');
                const minified = await fs.readJson(jsonFile);
                await fs.writeJson(versionedFile, minified);
                // 针对bundle.json使用gzip压一遍
                if (fileName == 'bundle') {
                    await gzip(versionedFile, versionedFile + '.gz');
                }
            }
            const jsonVer = (jsonInsteadOfAB == 'bundle' ? md5Book['bundle'] : JSON.stringify(md5Book));
            toolchain.buildInfo.jsonVersion = jsonVer;

            // 修改ResLoader.cs中的jsonVersion
            if (toolchain.option.platform == 'WebGL') {
                const resLoaderFile = path.join(toolchain.params.workSpacePath, CommonEnv.RESLOADER_CS);
                await replaceInFileOrThrow(resLoaderFile, 'JSON_VERSION_TO_BE_FILLED', jsonVer);
            }
        } else {
            console.log('skip');
        }
        return { success: true, errorCode: 0, data: void 0 };
    }
}
